<template>
	<view class="container">
		<!-- 标题 -->
		<!-- <view class="navbar ">
			<image src="/static/index_slices/back_left.png" mode="" @click="toBack"></image>
			<text>我要充值</text>

		</view> -->

		<view class="price-wrapper">

			<!-- 充值金额选择 -->
			<view class="price-crad">
				<view class="header">
					<image src="/otherPages/static/member.png" mode="widthFix"></image>
					<view class="">
						<text class="title">VIP会员套餐</text>
						<text>开通会员享各大特权，能赚更多</text>
					</view>
				</view>
				<up-tabs :list="priceList" keyName="name" lineColor="transparent" :itemStyle="itemStyle"
					@click="clickTab">
					<template #content="{item, keyName, index}">
						<view class="price-list" :class="{'price-list-active':activeIndex==index}">
							<text>充值金额</text>
							<text class="title"> {{item}}</text>
						</view>
					</template>
				</up-tabs>
				<!-- 立即开通按钮 -->
				<button @click="handleSubmit">立即开通</button>
			</view>

		</view>




		<!-- 会员权益列表 -->
		<view class="benefits">
			<view class="section-title">
				<image src="/otherPages/static/member_title.png" mode="widthFix"></image>
			</view>
			<view class="benefit-item" v-html="benefits"></view>
		</view>
		<pay-password v-model:visible="showPayPassword" :amount="payInfo?.order_amount" @complete="handlePayComplete"
			@forget="handleForgetPassword" />
	</view>
</template>

<script setup>
	import {
		ref,
		reactive
	} from 'vue';
	import CustomNavbar from '@/components/CustomNavbar.vue';
	import PayPassword from '@/components/PayPassword.vue';
	const showPayPassword = ref(false)
	const toBack = () => {
		uni.navigateBack({
			delta: 1 // 返回层数（默认1，表示返回上一页）
		});
	}
	const priceList = ref([])
	// 当前选中的金额索引
	const activeIndex = ref(0);

	// 会员权益列表
	const benefits = ref();

	// 选择金额
	const handleSelect = (index) => {
		activeIndex.value = index;
	};

	uni.$api.user.privileges().then(res => {
		if (res.code == 200) {
			benefits.value = res.data.desc
			priceList.value = res.data.recharge
		}
	})

	// 提交开通
	const handleSubmit = () => {
		uni.showLoading({
			title: '加载中……'
		})
		const selected = priceList.value[activeIndex.value];
		uni.$api.order.createOrder({
			goods_type: 0,
			goods_price: selected
		}).then(res => {
			if(res.code == 200){
				uni.navigateTo({
			url: '/orderPages/pages/order/pay-order?order_id=' + res.data.order_id
		})
			}
		})
		
		// uni.showToast({
		// 	title: `开通${selected}元套餐`,
		// 	icon: 'none'
		// });
	};
	// 支付方式
	const payIndex = ref(0)
	const payType = reactive([{
			type: '微信',
			icon: '/orderPages/static/wechat.png',
			checkIcon: '/orderPages/static/check.png',
			checkedIcon: '/orderPages/static/checked.png'
		},
		{
			type: '支付宝',
			icon: '/orderPages/static/alipay.png',
			checkIcon: '/orderPages/static/check.png',
			checkedIcon: '/orderPages/static/checked.png'
		},
		{
			type: '现金账户',
			icon: '/orderPages/static/cash.png',
			checkIcon: '/orderPages/static/check.png',
			checkedIcon: '/orderPages/static/checked.png'
		},
		{
			type: '复消账户',
			icon: '/orderPages/static/balance.png',
			checkIcon: '/orderPages/static/check.png',
			checkedIcon: '/orderPages/static/checked.png'
		},
		{
			type: '积分账户',
			icon: '/orderPages/static/balance.png',
			checkIcon: '/orderPages/static/check.png',
			checkedIcon: '/orderPages/static/checked.png'
		},
	])
	const payList = ref([])
	const selectPayType = (item, index) => {
		payIndex.value = index
	}
	const objValue = (obj) => {
		const valuesArray = Object.values(obj);
		const keysArray = Object.keys(obj);
		const objArr = valuesArray.map((item, i) => {
			return {
				id: keysArray[i],
				type: item
			}

		})

		return objArr;
	}
	const getPayType = () => {
		uni.$api.order.payType({
			id: id.value
		}).then(res => {
			if (res.code == 200) {
				payList.value = objValue(res.data.pay_type).map(item => {
					const matchedItem = payType.find(it => it.type == item.type);
					if (matchedItem) {
						return {
							...item,
							...matchedItem
						};
					}
				})
				payInfo.value = res.data.order
				startTimer()
			}
		})
	}
	
	// 支付完成回调
	const handlePayComplete = (password) => {
		uni.showLoading({
			title: '支付处理中...'
		})

		uni.hideLoading()
		uni.$api.order.payPwd({
			pay_password: password
		}).then(res => {
			if (res.code == 200) {
				console.log(0)
				onPay()
			}
			setTimeout(function() {
				showPayPassword.value = false

			}, 1000)
		}).catch(err => {
			setTimeout(function() {
				showPayPassword.value = false
			}, 1000)
		})
	}

	// 忘记密码
	const handleForgetPassword = () => {
		uni.showModal({
			title: '提示',
			content: '请通过安全中心重置支付密码',
			showCancel: false
		})
	}
	const buildQueryString = function(params) {
		// 步骤2：构建完整URL
		return `https://openapi.alipay.com/gateway.do?${
	  Object.keys(params)
	    .map(key => `${key}=${encodeURIComponent(params[key])}`)
	    .join('&')
	}`;;
	}

	// 支付
	const h5Pay = function(res) {
		// 微信H5支付
		if (payIndex.value) {
			window.location.href = `https://pay.weixin.qq.com?orderId=${payIndex.value.orderId}`;
			return;
		}

		// 支付宝H5支付
		if (!payIndex.value) {
			const divForm = document.getElementsByTagName('divform');
			if (divForm.length) {
				document.body.removeChild(divForm[0])
			}
			const div = document.createElement('divform');
			div.innerHTML = res; // data就是接口返回的form 表单字符串
			document.body.appendChild(div);
			let len = document.forms.length - 1;
			document.forms[len].setAttribute('target', '_blank'); // 新开窗口跳转
			document.forms[len].submit();
			return;
		}
	}

	const appPay = function(res) {
		const data = parseQueryString(res)
		uni.requestPayment({
			provider: payIndex.value ? 'alipay' : 'wxpay',
			orderInfo: JSON.stringify(data.biz_content),
			success: (res) => {
				console.log('支付成功', res);
				uni.showToast({
					title: '支付成功'
				});
			},
			fail: (err) => {
				console.log('支付失败', err);
				uni.showToast({
					title: '支付失败',
					icon: 'none'
				});
			}
		});
	}

	function parseQueryString(queryString) {
		return queryString.split('&').reduce((params, pair) => {
			const [key, value] = pair.split('=')
			params[key] = decodeURIComponent(value || '')
			return params
		}, {})
	}
	// 确认
	const query = () => {
		if (payList.value[payIndex.value].id > 2) {
			return showPayPassword.value = true;
		}
		onPay()

	}
	const onPay = () => {
		// #ifdef H5
		const method = 'wap';
		// #endif

		// #ifdef APP-PLUS
		const method = 'app'
		// #endif
		uni.$api.order.goPay({
			id: id.value,
			pay_type: payList.value[payIndex.value].id,
			method: method
		}).then(res => {
			if (res.code == 200) {
				if (payList.value[payIndex.value].id > 2) {
					uni.showToast({
						title: res.msg
					})
					setTimeout(function() {
						uni.navigateTo({
							url: '/orderPages/pages/order/pay-success'
						})
					}, 1000)
				} else {
					// #ifdef H5
					h5Pay(res.data);
					// #endif

					// #ifdef APP-PLUS
					appPay(res.data);
					// #endif
				}

			}
		})

	}

	const itemStyle = {
		height: "241rpx",
		padding: '0rpx'
	}
	const clickTab = (item, index) => {
		activeIndex.value = index;
	}
</script>

<style lang="scss" scoped>
	page {
		background-color: #111;
	}

	.container {
		background: url('/otherPages/static/member_bg.png') no-repeat;
		background-size: 100% auto;
		// padding-top: 28rpx; /* 导航栏高度 */
		padding-bottom: 112rpx;
	}

	.navbar {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		padding: 30rpx;
		color: #fff;
		z-index: 999;
		text-align: center;

		image {
			position: absolute;
			left: 30rpx;
			top: 30rpx;
			width: 20rpx;
			height: 38rpx;
		}
	}

	.price-wrapper {
		padding-top: 427rpx;

		.price-list {
			flex-shrink: 0;
			width: 205rpx;
			height: 241rpx;
			background: #fff;
			border-radius: 20rpx;
			margin-right: 14rpx;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			font-size: 26rpx;
			color: #222222;

			.title {
				font-size: 52rpx;
				color: #333333;
			}

		}

		.price-list-active {
			background-color: #FFF2DA;

			.activeTitle {
				color: #6A3313;
			}
		}

		.price-crad {
			margin: 0 20rpx;
			background: url('/otherPages/static/crad_bg.png');
			background-size: 100%;
			background-repeat: no-repeat;
			padding: 33rpx;
			padding-top: 0;

			.header {
				display: flex;
				text-align: left;
				align-items: center;
				font-size: 24rpx;
				color: #FFD8BA;
				padding-top: 30rpx;
				margin-bottom: 58rpx;

				image {
					width: 100rpx;
					margin-right: 21rpx;
				}

				.title {
					color: #FFF2DA;
					font-size: 32rpx;
					margin-bottom: 9rpx;
				}
			}

			.price {
				height: 241rpx;
				display: flex;

			}

			button {
				width: 624rpx;
				height: 88rpx;
				border-radius: 44rpx;
				background: linear-gradient(to right, #FAE6CB, #F1C596);
				margin-top: 51rpx;
			}
		}
	}

	.amount-card {
		background: #fff;
		border-radius: 16rpx;
		padding: 32rpx;
		margin: 16rpx 0;
		border: 2rpx solid #eee;
		position: relative;
		transition: all 0.3s;

		&.active {
			border-color: #ff4444;
			background: #fff5f5;
		}

		.amount {
			font-size: 40rpx;
			color: #333;
			font-weight: bold;
		}

		.tag {
			position: absolute;
			right: 20rpx;
			top: 20rpx;
			background: #ff4444;
			color: #fff;
			padding: 4rpx 12rpx;
			border-radius: 8rpx;
			font-size: 24rpx;
		}
	}

	.submit-btn {
		margin: 40rpx 0;
	}

	.benefits {
		background: linear-gradient(to right bottom, #4C4948, #2D2D2D);
		margin: 10rpx 20rpx;
		border-radius: 16rpx;
		padding: 62rpx 34rpx;

		.section-title {
			font-size: 32rpx;
			font-weight: bold;
			margin-bottom: 20rpx;
		}

		.benefit-item {
			font-size: 28rpx;
			color: #C6C6C6;
			line-height: 1.5;
			padding: 6rpx 0;
			margin: 0 34rpx;
			white-space: pre-wrap;
		}
	}
</style>